package com.cn.longdistancebusstation.scenic.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.BuildConfig;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.annotation.ScenicOrderState;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.ListResultV;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.ScenicOrderDetails;
import com.cn.longdistancebusstation.util.ToolUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by mucheng on 2018/4/24.
 */

public class ScenicOrderDetailsActivity extends BaseActivity implements View.OnClickListener{
    private TextView mOrderStatusTextView;
    private ImageView mQrcodeImageView;
    private TextView mQrcodeTextView;
    private TextView mVoucherCodeTextView;
    private TextView mTicketAmountPriceTextView;
    private TextView mOrderTitleTextView;
    private TextView mOrderTotalPriceTextView;
    private ImageView mOrderNoteImageView;
    private TextView mOrderIdTextView;
    private TextView mOnlineOrderTimeTextView;
    private ScenicOrderDetails mScenicOrderDetails;
    private TextView mUseSituationTextView;
    private TextView mUseSituationDetailsTextView;
    private RecyclerView mRecyclerView;
    private Button mRefundButton;
    private TouristAdapter mTouristAdapter;
    private String strTicketId;
    private ArrayList<Contacter> mContactersList=new ArrayList<>();
    private Button mPayOrderBtn,mCancleOrderBtn;
    private TextView mCheckTextView;
    private TextView mOrderInformationTextView;
    private String mScenicName,mTicketName;
    private LinearLayout mUseSituationLinearLayout;
    private TextView mMemoDetailsTextView;
    //订单号
    private String mOrderNo;
    //
    private @ScenicOrderState int orderState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scenic_order_details);
        getTitleTextView().setText("订单详情");
        initData();
        initView();
//        getOrderDetails();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderDetails();
    }

    private void initData(){
        Intent in=getIntent();
        strTicketId=in.getStringExtra("orderId");
    }
    private void initView() {
        mOrderStatusTextView=(TextView)findViewById(R.id.textView_status);
        mQrcodeImageView=(ImageView)findViewById(R.id.image_qrcode);
        mQrcodeTextView=(TextView)findViewById(R.id.qrcode);
        mVoucherCodeTextView=(TextView)findViewById(R.id.voucher_code);
        mTicketAmountPriceTextView=(TextView)findViewById(R.id.ticket_total_prices);
        mOrderTitleTextView=(TextView)findViewById(R.id.ticket_name);
        mOrderTotalPriceTextView=(TextView)findViewById(R.id.ticket_amount_price);
        mOrderInformationTextView=(TextView)findViewById(R.id.order_information);
        mOrderInformationTextView.setOnClickListener(this);
        mOrderNoteImageView=(ImageView)findViewById(R.id.order_note);
        mOrderNoteImageView.setOnClickListener(this);
        mOrderIdTextView=(TextView)findViewById(R.id.ticket_number);
        mMemoDetailsTextView=(TextView)findViewById(R.id.ticket_memo_details);
        mOnlineOrderTimeTextView=(TextView)findViewById(R.id.order_time);
        mUseSituationLinearLayout=(LinearLayout)findViewById(R.id.linearLayout_use_situation);
        mUseSituationTextView=(TextView)findViewById(R.id.ticket_use_situation);
        mUseSituationDetailsTextView=(TextView)findViewById(R.id.use_situation);
        mCheckTextView=(TextView)findViewById(R.id.check_refund);
        mPayOrderBtn=(Button)findViewById(R.id.button_pay);
        mPayOrderBtn.setOnClickListener(this);
        mRefundButton=(Button)findViewById(R.id.button_refund);
        mRefundButton.setOnClickListener(this);
        mCancleOrderBtn=(Button)findViewById(R.id.button_cancle_order);
        mCancleOrderBtn.setOnClickListener(this);
        mRecyclerView=(RecyclerView)findViewById(R.id.tourist_list);
        mTouristAdapter=new TouristAdapter();
        mRecyclerView.setAdapter(mTouristAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
    private void updateLayout(){
        switch (orderState)
        {
            case ScenicOrderState.SCENIC_ORDER_STATE_WAITING_PAY:
            {
                mOrderStatusTextView.setText("待付款");
                mPayOrderBtn.setVisibility(View.VISIBLE);
                mCancleOrderBtn.setVisibility(View.VISIBLE);
                mRefundButton.setVisibility(View.GONE);
                mQrcodeImageView.setVisibility(View.GONE);
                mQrcodeTextView.setVisibility(View.GONE);
                mVoucherCodeTextView.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.GONE);
                mUseSituationLinearLayout.setVisibility(View.GONE);
                mUseSituationTextView.setVisibility(View.GONE);
                mUseSituationDetailsTextView.setVisibility(View.GONE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_WAITING_USE:
            {
                mOrderStatusTextView.setText("待使用");
                mQrcodeImageView.setVisibility(View.VISIBLE);
                mQrcodeTextView.setVisibility(View.VISIBLE);
                mVoucherCodeTextView.setVisibility(View.VISIBLE);
                mUseSituationLinearLayout.setVisibility(View.VISIBLE);
                mUseSituationTextView.setVisibility(View.VISIBLE);
                mUseSituationDetailsTextView.setVisibility(View.VISIBLE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.VISIBLE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_CANCEL:
            {
                mOrderStatusTextView.setText("已取消");
                mQrcodeImageView.setVisibility(View.GONE);
                mQrcodeTextView.setVisibility(View.GONE);
                mVoucherCodeTextView.setVisibility(View.GONE);
                mUseSituationLinearLayout.setVisibility(View.GONE);
                mUseSituationTextView.setVisibility(View.GONE);
                mUseSituationDetailsTextView.setVisibility(View.GONE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.GONE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_USE:
            {
                mOrderStatusTextView.setText("已使用");
                mQrcodeImageView.setVisibility(View.VISIBLE);
                mQrcodeTextView.setVisibility(View.VISIBLE);
                mVoucherCodeTextView.setVisibility(View.VISIBLE);
                mUseSituationLinearLayout.setVisibility(View.VISIBLE);
                mUseSituationTextView.setVisibility(View.VISIBLE);
                mUseSituationDetailsTextView.setVisibility(View.VISIBLE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.VISIBLE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_REFUND:
            {
                mOrderStatusTextView.setText("已退票");
                mQrcodeImageView.setVisibility(View.GONE);
                mQrcodeTextView.setVisibility(View.GONE);
                mVoucherCodeTextView.setVisibility(View.GONE);
                mUseSituationLinearLayout.setVisibility(View.VISIBLE);
                mUseSituationTextView.setVisibility(View.VISIBLE);
                mUseSituationDetailsTextView.setVisibility(View.VISIBLE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.GONE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_EXCEPTION:
            {
                mOrderStatusTextView.setText("订单异常");
                mQrcodeImageView.setVisibility(View.GONE);
                mQrcodeTextView.setVisibility(View.GONE);
                mVoucherCodeTextView.setVisibility(View.GONE);
                mUseSituationLinearLayout.setVisibility(View.VISIBLE);
                mUseSituationTextView.setVisibility(View.VISIBLE);
                mUseSituationDetailsTextView.setVisibility(View.VISIBLE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.GONE);
                mCheckTextView.setVisibility(View.VISIBLE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_REFUNDING:
            {
                mOrderStatusTextView.setText("退票待审核");
                mQrcodeImageView.setVisibility(View.GONE);
                mQrcodeTextView.setVisibility(View.GONE);
                mVoucherCodeTextView.setVisibility(View.GONE);
                mUseSituationLinearLayout.setVisibility(View.VISIBLE);
                mUseSituationTextView.setVisibility(View.VISIBLE);
                mUseSituationDetailsTextView.setVisibility(View.VISIBLE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.GONE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
            case ScenicOrderState.SCENIC_ORDER_STATE_REFUND_FAILED:
            {
                mOrderStatusTextView.setText("退票失败");
                mQrcodeImageView.setVisibility(View.GONE);
                mQrcodeTextView.setVisibility(View.GONE);
                mVoucherCodeTextView.setVisibility(View.GONE);
                mUseSituationLinearLayout.setVisibility(View.VISIBLE);
                mUseSituationTextView.setVisibility(View.VISIBLE);
                mUseSituationDetailsTextView.setVisibility(View.VISIBLE);
                mPayOrderBtn.setVisibility(View.GONE);
                mCancleOrderBtn.setVisibility(View.GONE);
                mRefundButton.setVisibility(View.GONE);
                mCheckTextView.setVisibility(View.GONE);
            }
            break;
        }
    }
    /*
    * 获取订单详情
    * */
    private void getOrderDetails() {
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResultV<ScenicOrderDetails>> call=httpService.getScenicOrderDetails(strTicketId);
        call.enqueue(new Callback<ListResultV<ScenicOrderDetails>>() {
            @Override
            public void onResponse(Call<ListResultV<ScenicOrderDetails>> call, Response<ListResultV<ScenicOrderDetails>> response) {
                hideHud();
                ListResultV result=response.body();
                if(result!=null){
                    if(result.getHead().getSuccess()) {
                        Gson gson = new Gson();
                        Map<String, String> scenicMap = result.getBody().getData();
                        Type type = new TypeToken<ScenicOrderDetails>() {
                        }.getType();
                        String strScenicOrderJSON = new Gson().toJson(scenicMap);
                        mScenicOrderDetails = gson.fromJson(strScenicOrderJSON, type);
                        mScenicName = mScenicOrderDetails.getPltitle();
                        mTicketName = mScenicOrderDetails.getTtitle();
                        //订单状态
                        orderState = mScenicOrderDetails.getStatus();
                        //验证码
                        mVoucherCodeTextView.setText(mScenicOrderDetails.getCode());
                        //标题
                        mOrderTitleTextView.setText(mScenicOrderDetails.getPltitle()+"("+mScenicOrderDetails.getTtitle()+")"+mScenicOrderDetails.getNum()+"张");
                        //总价
                        mOrderTotalPriceTextView.setText(ToolUtil.fen2Yuan(mScenicOrderDetails.getTotalPrice())+"元");
                        //
                        mOrderIdTextView.setText(mScenicOrderDetails.getOrderId());
                        //订单时间
                        mOnlineOrderTimeTextView.setText(mScenicOrderDetails.getCreateTime());
                        //
                        int totalTicketCount = mScenicOrderDetails.getNum();
                        int useTicketCount = mScenicOrderDetails.getRealNum();
                        int refundTicketCount = mScenicOrderDetails.getReturnNum();
                        if(useTicketCount+refundTicketCount==totalTicketCount){
                            mRefundButton.setVisibility(View.GONE);
                        }else{
                            mRefundButton.setVisibility(View.VISIBLE);
                        }
                        mMemoDetailsTextView.setText(mScenicOrderDetails.getMemo());
                        mUseSituationDetailsTextView.setText("共"+totalTicketCount+"张,"+"已使用"+useTicketCount+"张,"+"已退"+refundTicketCount+"张");
                        //游客信息
                        String strTouristName = mScenicOrderDetails.getOrdername();
                        String strTouristCardNo = mScenicOrderDetails.getPersonID();
                        String strTouristTelephone = mScenicOrderDetails.getOrdertel();
                        String[] names = strTouristName.split(",");
                        String[] phones = strTouristTelephone.split(",");
                        String[] cardNos = strTouristCardNo.split(",");

                        mContactersList.clear();
                        for(int i=0; i<names.length; i++)
                        {
                            String strName = names[i];
                            String strPhone = phones[i];
                            String strCardNo = cardNos[i];
                            Contacter contacter = new Contacter();

                            contacter.setName(strName);
                            contacter.setTelephone(strPhone);
                            contacter.setCardNo(strCardNo);
                            mContactersList.add(contacter);
                        }
                        mTouristAdapter.notifyDataSetChanged();
                        //
                        updateLayout();
                        //获取二维码
                        getQRCodeImg();
                    }

                }

            }

            @Override
            public void onFailure(Call<ListResultV<ScenicOrderDetails>> call, Throwable t) {

            }
        });
    }

    private void getQRCodeImg() {
        String strRequestURL = mScenicOrderDetails.getQrcodeIMG();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(BuildConfig.SERVER_URL).addConverterFactory(ScalarsConverterFactory.create()).build();
        HttpService service=retrofit.create(HttpService.class);
        Call<String> call=service.getQRCode(strRequestURL);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String strImgPath = response.body();
                String[] arr = strImgPath.split("\'");
                Picasso.with(ScenicOrderDetailsActivity.this).load(arr[1]).placeholder(R.mipmap.pre_loading)
                        .error(R.mipmap.pre_loading).noFade().into(mQrcodeImageView);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.order_note:
                Intent in=new Intent(ScenicOrderDetailsActivity.this,ScheduleNoteActivity.class);
                startActivity(in);
                break;
            case R.id.button_refund:
                refund();
                break;
            case R.id.button_pay:
                payOrder();
                break;
            case R.id.button_cancle_order:
                cancleOrder();
                break;
            case R.id.order_information:
                Intent intent=new Intent(ScenicOrderDetailsActivity.this,ScheduleNoteActivity.class);
                startActivity(intent);
                break;

        }


    }

    private void refund() {
        showHud("正在退票，请稍后");
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        String strPFTOrderNo = mScenicOrderDetails.getPftOrderNum();
        Call<Result> call=httpService.refund(strPFTOrderNo,strTicketId,mScenicOrderDetails.getRealNum()+"");
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                if(result!=null){
                    Boolean isSuccess=result.getHead().getSuccess();
                    if(isSuccess){
                        getOrderDetails();
                    }else{
                        Toast.makeText(ScenicOrderDetailsActivity.this,"退票失败",Toast.LENGTH_SHORT).show();
                    }

                }

            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(ScenicOrderDetailsActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void payOrder() {
        Intent in=new Intent(ScenicOrderDetailsActivity.this, TicketOrderPaymentActivity.class);
        in.putExtra("orderNo",mScenicOrderDetails.getOrderId());
        in.putExtra("scenicName",mScenicName);
        in.putExtra("ticketName",mTicketName);
        in.putExtra("totalAmount", ToolUtil.fen2Yuan(mScenicOrderDetails.getTotalPrice()));
        startActivity(in);
    }
    private void cancleOrder(){
        showHud("正在取消订单，请稍后");
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<Result> call=httpService.getCancleOrder(strTicketId);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                if(result!=null){
                    Boolean isSuccess=result.getHead().getSuccess();
                    if(isSuccess){
                        Toast.makeText(ScenicOrderDetailsActivity.this,"取消订单成功",Toast.LENGTH_SHORT).show();
                        getOrderDetails();
                    }else{
                        Toast.makeText(ScenicOrderDetailsActivity.this,"取消订单失败",Toast.LENGTH_SHORT).show();
                    }

                }

            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(ScenicOrderDetailsActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private class TouristAdapter extends RecyclerView.Adapter<TouristViewHolder>{
        @Override
        public TouristViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(ScenicOrderDetailsActivity.this);
            View view = layoutInflater.inflate(R.layout.tourist_info_recycle_item, parent, false);
            return new TouristViewHolder(view);
        }

        @Override
        public void onBindViewHolder(TouristViewHolder holder, int position) {
            Contacter contacter=mContactersList.get(position);
            holder.bindData(contacter);

        }

        @Override
        public int getItemCount() {
            return mContactersList.size();
        }
    }

    private class TouristViewHolder extends RecyclerView.ViewHolder{
        private TextView mTouristNameTextView;
        private TextView mTouristIdcardNoTextView;
        private TextView mtouristTelephoneTextView;
        public TouristViewHolder(View itemView) {
            super(itemView);
            mTouristNameTextView=(TextView)itemView.findViewById(R.id.tourist_name);
            mTouristIdcardNoTextView=(TextView)itemView.findViewById(R.id.idcard_numbers);
            mtouristTelephoneTextView=(TextView)itemView.findViewById(R.id.telephone_number_details);
        }

        public void bindData(Contacter contacter) {
            mTouristNameTextView.setText(contacter.getName());
            mTouristIdcardNoTextView.setText(contacter.getCardNo());
            mtouristTelephoneTextView.setText(contacter.getTelephone());

        }
    }

}
